import {Component, ElementRef, OnInit, OnDestroy, ViewChild} from '@angular/core';
import {TreeNode} from "primeng/primeng";
import {LocationService} from "../location.service";

@Component({
  selector: 'app-realtime-monitor',
  templateUrl: './realtime-monitor.component.html',
  // template: 'canvas(id="videostream1" width="320" height="240" style="border:solid;")',
  styleUrls: ['./realtime-monitor.component.css']
})
export class RealtimeMonitorComponent implements OnInit, OnDestroy{
  orgs: TreeNode[];//组织树的数据
  selected: TreeNode;                     // 被选中的节点
  selectedNode: any = {};                     // 组织树被选中的节点
  private myCanvas: any;
  private newCanvas: any;
  context;
  newContext;
  count;
  intervalObj;

  @ViewChild("myCanvas") myCanvasElem: ElementRef;
  @ViewChild("newCanvas") newCanvasElem: ElementRef;

  constructor(
    private locationService: LocationService) {
    }

  ngOnInit() {
    //查询标签定位树
    this.queryTagTree({});

    this.newCanvas = this.newCanvasElem.nativeElement
    this.newContext = this.newCanvas.getContext("2d");
    let backgroundImg = new Image();
    backgroundImg.src = "./data/background.png";
    let that = this;
    backgroundImg.onload = function () {
      // that.newContext.drawImage(backgroundImg,0,0,725,347,0,0,that.newCanvas.width,that.newCanvas.height)
      that.newContext.drawImage(backgroundImg,0,0,that.newCanvas.width,that.newCanvas.height)
    }

    this.myCanvas = this.myCanvasElem.nativeElement
    this.context = this.myCanvas.getContext("2d");

    this.intervalObj = setInterval(function () {
      that.clearMap();
      that.move2D(that.context);//画标签
    },40)
  }

  clearMap(){
    this.context.clearRect(0, 0, this.myCanvas.width, this.myCanvas.height);
    /*contex_ruler_top.clearRect(0, 0, canvas_ruler_top.width, canvas_ruler_top.height);
    contex_ruler_left.clearRect(0, 0, canvas_ruler_left.width, canvas_ruler_left.height);*/
    // context.clearRect(0, 0, 3050, 3050);
    // contex_ruler_top.clearRect(0, 0, 3050, 100);
    // contex_ruler_left.clearRect(0, 0, 100, 3050);
  }

  move2D(context){
    /*let x = Math.random() * 100;
    let y = Math.random() * 100;
    this.drawPosition(context,"",x, y,"rgba(255,0,0,1)")*/
    //请求数据
    // let cids = ["1"];
    let cids = [];
    // let colorData = ["rgba(255,0,0,1)","rgba(0,0,255,1)"]
    this.locationService.getTagLocationInfo(cids).subscribe(data => {
      console.log(data);
      for (let i = 0, len = data.length;i < len;i++){
        this.drawPosition(context,"",data[i].x / 60, data[i].y / 60, "rgba(255,0,0,1)")
      }
    })
    /*$.get("http://localhost:8080/real_time_coor",
      function(data,status){
        if(status == "success"){
          //var res1=eval("("+data+")");
          var res1=data;
          for (var i = 0; i < res1.length; i++) {
            var res = res1[i];
            x = res.x;
            y = res.y;
            x_filter = res.x_filter;
            y_filter = res.y_filter;
            if(res.lab_id == lab_id_){
              pos_bs_ip1 =  res.bss[0].ip;
              pos_bs_ip2 =  res.bss[1].ip;
              pos_bs_dis1 =  res.bss[0].dis_f;
              pos_bs_dis2 =  res.bss[1].dis_f;
            }
            // pos_bs_id1 =  res.bss[0].id
            // pos_bs_id2 =  res.bss[1].id
            // pos_bs_dis1 =  res.bss[0].lab_dist
            // pos_bs_dis2 =  res.bss[1].lab_dist

            //distance_p3 = res.r3
            drawPosition(context,"",x, y,"rgba(204,0,51,0.1)")
            drawPosition(context,"id"+res.lab_id,x_filter, y_filter,"rgba(204,0,51,1)")
          }

        }
      });*/
  }

  //在地图上画点
  drawPosition(context,name,x,y,color){
    //基站坐标比例缩放
    let zoom = 1;
    let x_ = x*zoom;
    let y_ = y*zoom;

    context.beginPath();
    context.arc(x_, y_, 5, 0, Math.PI * 2, true);
    //不关闭路径路径会一直保留下去，当然也可以利用这个特点做出意想不到的效果
    context.fillStyle = color;
    context.fill();
    context.closePath();

    context.fillText(name+"("+(x)+","+(y)+")", x_+20,y_+20)
  }

  //查询
  queryTagTreeData(){

  }

  //查询组织树数据
  queryTagTree(tag){
    this.locationService.getTagTree(tag).subscribe(data => {
      // console.log(data);
      /*data = [
        {
          label: "广电中心机房",
          children:[
            {label:"A机房区域",children:[
              {label:"标签1&张三", icon: "fas fa-signal"},
              {label:"标签2&李四"},
              {label:"标签3&王五"},
            ]},
            {label:"B机房区域", children: [
              {label:"标签4&老王"},
            ]},
          ]
        }
      ];*/
      this.orgs = data;
      if(data){
        this.expandAll(data)
      }
    })
  }

  expandAll(treeDatas){
    treeDatas.forEach(node => {
      this.expandRecursive(node, node.open == "false" ? false : true);
    })
  }

  expandRecursive(node: TreeNode, isExpand: boolean){
    node.expanded = isExpand;
    if(node.children){
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, childNode["open"] == "false" ? false : true)
      })
    }
  }

  // 树展开
  nodeExpand(event) {
    console.log(event.node)
    let node = {
      "cid": "",
      "label": "",
      "dep": "",
      "nid": "",
      "father_nid": "",
      "node_type": "",
      "remark": "",
      "del": "",
      "open": ""

    };
    for(let key in node){
      node[key] = event.node[key];
    }
    node["open"] = "true";
    console.log(node)
    this.locationService.updateNodeStatus(node).subscribe( data => {

    })
  }

  // 树折叠
  nodeCollapse(event) {
    console.log(event.node)
    let node = {
      "cid": "",
      "label": "",
      "dep": "",
      "nid": "",
      "father_nid": "",
      "node_type": "",
      "remark": "",
      "del": "",
      "open": ""

    };
    for(let key in node){
      node[key] = event.node[key];
    }
    node["open"] = "false";
    console.log(node)
    this.locationService.updateNodeStatus(node).subscribe( data => {

    })
  }

  //销毁组件时清除定时器

  ngOnDestroy(){
    if(this.intervalObj){
      clearInterval(this.intervalObj);
    }
  }

}
